<div class="row gap-20 masonry pos-r">
	<div class="masonry-sizer col-md-12"></div>
	<div class="masonry-item col-md-6">
		<div class="bgc-white p-20 bd">
			<h6 class="c-grey-900" th:text="#{service.admin.new}"></h6>
			<div class="mT-30">
				<form id="serviceForm" name="serviceForm" role="form" th:object="${serviceForm}" th:action="@{/saveservice}" method="post" enctype="multipart/form-data">
				
					<input type='hidden' class='primarykey' id="idService" th:field="*{idService}">
					
					<div class="form-row">
						<div class="form-group col-md-6"><label for="nameService"
							th:text="#{form.service.name}"></label> <span id="nameService_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span> <input type="text"
							class="form-control" id="nameService" th:field="*{name}" max="100" required>
					</div>
						<div class="form-group col-md-6"><label for="platform" th:text="#{form.service.platform}"></label>
						 <select id="platform" class="form-control" th:field="*{platform}" required>
								<option selected="selected" value="-1" th:text="#{form.service.select.platform}"></option>
								<option th:each="p: ${platforms}" th:value="${p.idPlatform}" th:text="${p.name}"></option>
						</select>
						</div>
					</div>
					<div class="form-row">
						<div class="col-md-4">
							<label for="serviceTypes" th:text="#{form.service.servicetype}"></label>
						</div>
						<div class="col-md-8">
							<label for="endpoint" th:text="#{form.service.endpoint}"></label> 
						</div>
					</div>
					<div class="form-row">
						<div id="serviceTypesContainer" class="form-group col-md-3">
							<select id="serviceTypes" class="form-control"
							th:field="*{serviceType}" required>
								<option selected="selected" value="-1" th:text="#{form.service.select.servicetype}"></option>
								<option th:each="ts: ${serviceTypes}" th:value="${ts}" th:text="#{ts}"></option>
							</select>
						</div>
						<div class="form-group col-md-6">
							<input type="text" class="form-control" alt id="endpoint" readonly>
						</div>
						<div class="form-group col-md-3">
							<span id="nameWsdl_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span>
							<input type="text" class="form-control" id="nameWsdl" th:field="*{nameWsdl}" required>
						</div>
					</div>
					<div class="form-row">
						<div class="form-group col-md-6">
							<label for="timeout" th:text="#{form.service.timeout}"></label> 
							<span id="timeout_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span> 
							<input type="text" class="form-control" id="timeout" th:field="*{timeout}"	required>
						</div>
						<div class="form-group col-md-6">
						<label for="timer"	th:text="#{form.service.timer}"></label> 
						<select id="timer"	class="form-control" th:field="*{timer}" required>
								<option selected="selected" value="-1"	th:text="#{form.service.select.timer}"></option>
								<option th:each="t: ${timers}" th:value="${t.idTimer}" th:text="${t.name}"></option>
						</select></div>
					</div>
					<div class="form-row">
						<div class="form-group col-md-6">
							<label for="uDegraded" th:text="#{form.service.udegraded}"></label> 
							<span id="uDegraded_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span> 
							<input type="text" class="form-control" id="uDegraded" th:field="*{degradedThreshold}" required>
						</div>
						<div class="form-group col-md-6">
							<label for="uLost" th:text="#{form.service.ulost}"></label> 
							<span id="uLost_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span> 
							<input type="text" class="form-control" id="uLost" th:field="*{lostThreshold}" required>
						</div>
					</div>
					
					<div class="form-row">
						<div class="form-group col-md-6"><label for="alarm"
							th:text="#{form.service.alarm}"></label> <select id="alarm"
							class="form-control" th:field="*{alarm}" required>
								<option selected="selected" value="-1"
									th:text="#{form.service.select.alarm}"></option>
								<option th:each="p: ${alarms}" th:value="${p.idAlarm}"
									th:text="${p.name}">
								</option>
							</select>
						</div>
					</div>

					<div class="form-row">
						<div class="form-group">
						<label for="file" th:text="#{form.service.file}"></label> 
								<div class="custom-file" id="customFile" lang="es">
									<input type="file" class="custom-file-input" id="file" th:field="*{file}" aria-describedby="fileHelp">
									<label class="custom-file-label" for="file" th:text="#{form.ssl.file.choose}"></label>
								</div>
								<span id="file_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span>
							<div style="clear: both;" />
						</div>
					</div>
					
					<input type='hidden' class='primarykey' id="idFile" th:field="*{idFile}">
					<input type='hidden' class='primarykey' id="fileData" th:field="*{fileData}">

					<button id="serviceBtn" type="submit" class="btn btn-primary" th:text="#{button.save}"></button>
					<button id="cleanServiceBtn" class="btn btn-primary" onclick="cleanServiceForm();" th:text="#{button.cleanForm}"></button>
				</form>
		</div>
	</div>

</div>
	<div class="masonry-item col-md-6">
		<div class="bgc-white p-20 bd">
			<h6 class="c-grey-900" th:text="#{timer.admin.new}"></h6>
			<div class="mT-30">
				<form id="timerForm" th:object="${timerform}" th:action="@{/savetimer}" method="post">
					<input type='hidden' class='primarykey' id="idTimer" th:field="*{idTimer}">
					<input type='hidden' id="frequency" th:field="*{frequency}">
					
					<div class="form-row">
						<div class="form-group col-md-6">
							<label for="nameTimer" th:text="#{form.timer.name}"></label> 
							<span id="nameTimer_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span> 
							<input type="text" class="form-control" id="nameTimer" th:field="*{name}" required>
						</div>
						<div class="form-group col-md-6">
							<label for="frequencyTime" th:text="#{form.timer.frequency}"></label> 
							<span id="frequency_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span> 
							<input type="time" class="form-control" id="frequencyTime" th:field="*{frequencyTime}" step="1"	required>
						</div>
					</div>
					<button id="timerBtn" type="submit" class="btn btn-primary" th:text="#{button.save}"></button>
					<button id="cleanTimerBtn" class="btn btn-primary" onclick="cleanForm('#timerForm');" th:text="#{button.cleanForm}"></button>
				</form>
			</div>
		</div>
		<div class="bgc-white bd bdrs-3 p-20 mB-20">
			<h6 class="c-grey-900 mB-20" th:text="#{table.timer.title}"></h6>
			<table id="timerTable" class="table table-striped table-bordered"
				cellspacing="0" width="100%">
				<thead>
					<tr>
						<!-- Columna oculta para el identificador de la plataforma -->
						<th></th>
						<th th:text="#{table.timer.name}"></th>
						<th th:text="#{table.timer.frequency}"></th>
					</tr>
				</thead>
			</table>
	</div>
</div>
	<div class="masonry-item col-md-12">
		<div class="bgc-white bd bdrs-3 p-20 mB-20">
			<h4 class="c-grey-900 mB-20" th:text="#{table.service.title}"></h4>
			<table id="serviceTable" class="table table-striped table-bordered"
				cellspacing="0" width="100%">
				<thead>
					<tr>
						<!-- Columna oculta para el identificador del servicio -->
						<th></th>
						<th th:text="#{table.service.name}"></th>
						<th th:text="#{table.service.timeout}"></th>
						<th th:text="#{table.service.endpoint}"></th>
						<!-- Columna oculta para el identificador de la plataforma -->
						<th></th>
						<th th:text="#{table.service.platform}"></th>
						<!-- Columna oculta para el identificador del timer -->
						<th></th>
						<th th:text="#{table.service.timer}"></th>
						<th th:text="#{table.service.udegraded}"></th>
						<th th:text="#{table.service.ulost}"></th>
						<th th:text="#{table.service.serviceType}"></th>
						<!-- Columna oculta para el identificador de la alarma -->
						<th></th>
						<th th:text="#{table.service.alarm}"></th>
						<!-- Columna oculta para el nombre del fichero -->
						<th></th>
						<th th:text="#{table.service.file}"></th>
					</tr>
				</thead>
			</table>
	</div>
</div>
</div>

<script th:inline="javascript">

//Carga los tipos de servicio al seleccionar una plataforma
var urlLoadServiceTypes = /*[[@{/loadservicetype}]]*/;
var selectServiceTypeText = /*[[#{form.service.select.servicetype}]]*/;

function typeServiceChange(idPlatform, serviceType){
	var urlLoadBaseEndpoint = /*[[@{/loadbaseendpoint}]]*/;
	
	$.ajax(urlLoadBaseEndpoint,{
		data:$.param({'idPlatform':idPlatform, 'serviceType': serviceType}),
		type:'GET',
		success: function(data){
			$('#endpoint').attr('value', data.response);
		},
		error:function(){}
	});
	
}
$(document).ready(function() {
		
	
	$('#platform').change(
	        function() {
	            $.getJSON(urlLoadServiceTypes, {
	            	idPlatform : $(this).val()
	            }, function(data) {
	                var html = '<option value="">' + selectServiceTypeText + '</option>';
	                var len = data.length;
	                for ( var i = 0; i < len; i++) {
	                    html += '<option value="' + data[i] + '">'
	                            + data[i] + '</option>';
	                }
	                html += '</option>';
	                $('#serviceTypes').html(html);
	                $('#endpoint').attr('value', '');
	            });
	        });
	
	// Establece la base del endpoint al seleccionar tipo de servicio (+ plataforma previamente)
	var urlLoadBaseEndpoint = /*[[@{/loadbaseendpoint}]]*/;
	$('#serviceTypes').change(
				
	        function() {
				hide();
			
	            $.getJSON(urlLoadBaseEndpoint, {
	            	idPlatform : $('#platform').val(),
	            	serviceType : $('#serviceTypes').val()
	            }, function(data) {
	               $('#endpoint').attr('value', data.response);
	               
	               checkIfDisabledEndpoint($('#serviceTypes').val());
	               
	            });
	        });
	// Gestión de las datatables
	
	var actionDeleteService = /*[[@{/deleteservice}]]*/;
	var getservices = /*[[@{/servicesdatatable}]]*/;
	var tblService = $('#serviceTable').DataTable({
		dom: 'Bfrtip',
	    select: 'single',
	    responsive: true,
	    altEditor: true,
	    buttons: [{extend: 'selected',text: 'Editar',name: 'editPageForm',
	    	action: function ( e, dt, node, config ) {
				// Para el action 'Editar' obtenemos los valores de la fila seleccioanda
				// directamente y los copiamos al formulario
				for (var o = dt, a = [], e = 0; e < o.context[0].aoColumns.length; e++) a.push({
	                id: o.context[0].aoColumns[e].mData,
	            	title: o.context[0].aoColumns[e].sTitle                
	            });
				var d = dt.rows({
                    selected: !0
                })
                
				hide();
				
                var idService = d.data()[0][a[0].id]
				var nameService = d.data()[0][a[1].id]
				var timeoutValue = d.data()[0][a[2].id]
                var nameWsdl = d.data()[0][a[3].id]
                var idPlatform = d.data()[0].platform.idPlatform
                var idTimer = d.data()[0].timer.idTimer
                var degradedThresholdValue = d.data()[0][a[8].id]
                var lostThresholdValue = d.data()[0][a[9].id]
                var serviceType = d.data()[0][a[10].id]
                
                if (d.data()[0].requestFile != null) {
					var fileName = d.data()[0].requestFile.filename
                }
				
				var idAlarm = d.data()[0].alarm.idAlarm
				var idFile;
				
				if (d.data()[0].requestFile == null) {
					idFile = null;
				} else {
					idFile = d.data()[0].requestFile.idRequestServiceFile;
				}				
								
				$("#idService").val(idService);
				$("#idFile").val(idFile);
                $("#nameService").val(nameService);
                $("#timeout").val(timeoutValue);
                $("#platform").val(idPlatform);
                $("#nameWsdl").val(nameWsdl);
                loadEditServiceTypes(idPlatform, serviceType);
                typeServiceChange(idPlatform, serviceType);
                $("#timer").val(idTimer);
                $("#uDegraded").val(degradedThresholdValue);
                $("#uLost").val(lostThresholdValue);
                $("#alarm").val(idAlarm);
				$("#idFile").val(idFile);
				
				$(".custom-file-label").attr('data-content', fileName);
				$(".custom-file-label").text(fileName);
				
				checkIfDisabledEndpoint(serviceType);
                
			}
	    }, {extend: 'selected',text: 'Eliminar',name: 'delete'}],
	
	    "iTotalRecords": "totalElements",
        "iTotalDisplayRecords": "numberOfElements",
	    
		"processing": true,
	    "serverSide": true,
		"ajax": {
	        "url": getservices,
	        "dataSrc" : "data",
	        "data": function (data) {
	        	// Datos a pasar al modal
	            data.formId = "serviceForm";
	        }
	      },
	    "language": {
	        "url": "js/datatables/i18n/spanish.json",
	        select: {
	            rows: {
	                _: "%d filas seleccionadas",
	                1: "1 fila seleccionada"
	            }
	          }
	        },
		"columns": [
	        { "data": "idService",
	          "visible": false},
	        { "data": "name" },
	        { "data": "timeout" },
	        { "data": "nameWsdl" },
	        { "data": "platform.idPlatform",
	          "visible": false},
	        { "data": "platform.name"},
	        { "data": "timer.idTimer",
	          "visible": false},
	        { "data": "timer.name"},
	        { "data": "degradedThreshold"},
	        { "data": "lostThreshold"},
	        { "data": "serviceType" },
	        { "data": "alarm.idAlarm",
	          "visible": false},
	        { "data": "alarm.name"},
	        { "data": "requestFile.filename",
				  "visible": false,
				  "defaultContent": ""},
	        { "data": "requestFile.idRequestServiceFile", 
	        	"render": function (data, type, row) {	
				
	        		if (data != null && data != '' && data != 'undefined') {
						var filename = row.requestFile.filename;
	        			return '<a id="download" target="_blank" onclick="downloadFile(' + data + ',\'' + filename + '\');"><span class="icon-holder"><i class="c-green-500 ti-download pointer"></i></span></a>';
	        		} else {
						return 'Sin peticiones';
					}
	        	}
	        }
	        ]
		}).on('crudaction', function(e, accion, idService, data, rowindex){
		    // e          Evento Jquery
		    // accion     [add|edit|delete]
		    // pkid       Primer campo en la data [id]                ... en add,    retorna null
		    // data       Los campos adicionales  [campo_1, campo_n]  ... en delete, retorna null
		    // rowindex   El index de la fila para el dataTable       ... en add,    retorna null
		    
		    $('#altEditor-modal .modal-body .alert').remove();
		    // Se muestra la capa 'cargando...'
		    loading();
		    
		    switch(accion){
		        case 'delete':
		        	var type = $('form[name="altEditor-form"] input').attr('id');
		        	if (type == 'idService'){
		        		$.ajax(actionDeleteService,{
			            	data:$.param({'id':idService, 'index':rowindex}),
			                type:'POST',
			                success: function(data){
			                    
			                	if (data == "-1" && $('#errorModalService').length == 0){
			                		$('#serviceForm').append('<div id="errorModalService" class="alert alert-danger" role="alert"><strong>' + [[#{service.admin.error.inUse}]] + '</strong></div>');
			                	}else{
									$('#errorModalService').remove();
								}
			                	
			                	// Se oculta la capa 'cargando...'
			                	hide();
			                    tblService.row(data.index).remove().draw();
			                    
			                    $('#altEditor-modal .modal-body .alert').remove();
			                    $('#altEditor-modal').modal('hide');
			                },
			                error:function(){}
			            });
		        	}else{
						// Se oculta la capa 'cargando...'
						hide();
					}
		            break;
		        default:
		            $('#altEditor-modal .modal-body .alert').remove();
		            $('#altEditor-modal .modal-body').append('<div class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.NotAuthorized}]] + '</strong></div>');
		            break;
		    }
		});
	
	var gettimers = /*[[@{/timersdatatable}]]*/;
	var actionDeleteTimer = /*[[@{/deletetimer}]]*/;
	var tblTimer = $('#timerTable').DataTable({
		dom: 'Bfrtip',
	    select: 'single',
	    responsive: true,
	    
	    altEditor: true,
	    buttons: [{extend: 'selected',text: 'Editar',name: 'editPageForm',
	    			action: function ( e, dt, node, config ) {
	    				// Para el action 'Editar' obtenemos los valores de la fila seleccioanda
	    				// directamente y los copiamos al formulario
	    				for (var o = dt, a = [], e = 0; e < o.context[0].aoColumns.length; e++) a.push({
	    	                id: o.context[0].aoColumns[e].mData,
	    	            	title: o.context[0].aoColumns[e].sTitle                
	    	            });
	    				var d = dt.rows({
	                        selected: !0
	                    })
						
	                    var idTimer = d.data()[0][a[0].id]
	    				var nameTimer = d.data()[0][a[1].id]
	    				var freqValue = d.data()[0][a[2].id]
	    				
	    				var freqTimer = millisecondToTime(freqValue);
	    				
	    				$("#idTimer").val(idTimer);
	    				$("#frequency").val(freqValue);
	    				$("#nameTimer").val(nameTimer);
	    				$("#frequencyTime").val(freqTimer);
	    				
	    				}
	    		  }, {extend: 'selected', text: 'Eliminar', name: 'delete'}],
		
		"iTotalRecords": "totalElements",
        "iTotalDisplayRecords": "numberOfElements",
        "pageLength": 5,
	    
		"processing": true,
	    "serverSide": true,
		"ajax": {
	        "url": gettimers,
	        "dataSrc" : "data",
	        "data": function (data) {
	        	// Datos a pasar al modal
	            data.formId = "timerForm";
	        }
	      },
	    "language": {
	        "url": "js/datatables/i18n/spanish.json",
	        select: {
	            rows: {
	                _: "%d filas seleccionadas",
	                1: "1 fila seleccionada"
	            }
	          }
	        },
		"columns": [
	        { "data": "idTimer",
	          "visible": false},
	        { "data": "name" },
	        { "data": "frequency",
	          "render": function ( data, type, row ) {
						return millisecondToTime(data);
					}
			}
	        ]
		}).on('crudaction', function(e, accion, idTimer, data, rowindex){
		    // e          Evento Jquery
		    // accion     [add|edit|delete]
		    // pkid       Primer campo en la data [id]                ... en add,    retorna null
		    // data       Los campos adicionales  [campo_1, campo_n]  ... en delete, retorna null
		    // rowindex   El index de la fila para el dataTable       ... en add,    retorna null
		    $('#altEditor-modal .modal-body .alert').remove();
		    // Se muestra la capa 'cargando...'
		    loading();
		    switch(accion){
		        case 'delete':
		        	var type = $('form[name="altEditor-form"] input').attr('id');
		        	if (type == 'idTimer'){
			        	$.ajax(actionDeleteTimer, {
			            	data:$.param({'id':idTimer, 'index':rowindex}),
			                type:'POST',
			                success: function(data){
			                    
			                	if (data == "-1" && $('#errorModalTimer').length == 0){
			                		$('#timerForm').append('<div id="errorModalTimer" class="alert alert-danger" role="alert"><strong>' + [[#{timer.admin.error.inUse}]] + '</strong></div>');
			                	}else{
									$('#errorModalTimer').remove();
								}
			                	// Se oculta la capa 'cargando...'
			                	hide();
			                	tblTimer.row(data.index).remove().draw();
			                    
			                    $('#altEditor-modal .modal-body .alert').remove();
			                    $('#altEditor-modal').modal('hide');
			                },
			                error:function(){}
			            });
		        	}else{
						// Se oculta la capa 'cargando...'
						hide();
					}
		            break;
		        default:
		            $('#altEditor-modal .modal-body .alert').remove();
		            $('#altEditor-modal .modal-body').append('<div class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.NotAuthorized}]] + '</strong></div>');
		            break;
		    }
		});
	
	// Control del botón para guardar un timer
	$( "#timerBtn" ).click(function( event ) {
	  event.preventDefault();
	
	  var freq = checkTypeTime($('#frequencyTime'));
	  if (freq != $('#frequencyTime')[0].value){
	    $("#timerForm input")[3].value = freq;
	  }
		
	  $("#timerForm input")[1].value = timeToMillisecond(freq);
	  
	  var formData = JSON.stringify($("#timerForm").serializeJSON());
	  var url = /*[[@{/savetimer}]]*/;
	  
	  loading();
	  if ($('#timerForm')[0].checkValidity() === false) {
		  hide();
		  
		  $('#timerForm *').filter(':input').each(function(){
      	    
          	if(!$(this)[0].checkValidity()){
      	  	 	$("#" + $(this).attr('id')).addClass("has-error");
      	    } else {
      	  	 	$("#" + $(this).attr('id')).removeClass("has-error");
      	    }
      	    
      	  });
		  
	  } else{
		  $.ajax({
			  type: "POST",
			  url: url,
			  data: formData,
			  success: function(data){
				  var errores = JSON.parse(data.error);
				  
				  if (data.error != null){
					  jQuery.each(errores, function(i, val) {
					  	$('#timerForm *').filter('span').each(function(){
							if (i == $(this).attr('id')){
								$("#" + i).text(val);
							}
						});
					  });
				  }else{
					  $("#timerForm")[0].reset();
					  cleanForm('#timerForm');
					  $('#timerForm *').filter('span').each(function(){
						$(this).text('');
					  });
					  
					  $('#timer').append($('<option>', {
					    value: $(data.data)[0].idTimer,
					    text: $(data.data)[0].name
					  }));
					  
					  tblTimer.row.add($(data.data)).draw(false);
				  }
				  
				  hide();
				  
				   $('#timerForm *').filter(':input').each(function(){
					 $("#" + $(this).attr('id')).removeClass("has-error");
				   });
				   
				   if ($('#errorModalTimer').length > 0){
					 $('#errorModalTimer').remove();
				   }
				  
			  },
			  error:function(){
				  $('#errorModalTimer').remove();
				  hide();
				  if (checkTypeTime($('#frequencyTime')) == $('#frequencyTime')[0].value){
					$('#timerForm').append('<div id="errorModalTimer" class="alert alert-danger" role="alert"><strong>' + [[#{timer.admin.error.badFormat}]] + '</strong></div>');
				  }
				  
				  if ($('#errorModalTimer').length == 0){
				  	$('#timerForm').append('<div id="errorModalTimer" class="alert alert-danger" role="alert"><strong>' + [[#{timer.admin.error.sameName}]] + '</strong></div>');
				  }
			  },
			  dataType: "json",
			  contentType : "application/json"
			});
	  }
	  
	});
	
	// Control del botón para guardar un servicio
	$( "#serviceForm" ).submit(function( event ) {
	  event.preventDefault();
	 	  
	  //var formData = JSON.stringify($("#serviceForm").serializeJSON());
	  
	  var formData = new FormData();
	  var file =  $('#file').prop('files')[0];
	  var blob = new Blob([JSON.stringify($("#serviceForm").serializeJSON())], {type: "application/json"});
	  
	  hide();
	  
	  if (file == undefined) {
			file = new File([""], "nofile", {type: "text/plain", lastModified: new Date()});
	  }
	  formData.append("file", file);
	  formData.append('serviceForm', blob);
	
	  var saveserviceaction = /*[[@{/saveservice}]]*/;
	  
	  loading();
	  
	  if ($('#serviceForm')[0].checkValidity() === false) {
		  hide();
		  
		  $('#serviceForm *').filter(':input').each(function(){
      	    
          	if(!$(this)[0].checkValidity()){
      	  	 	$("#" + $(this).attr('id')).addClass("has-error");
				
      	    } else {
      	  	 	$("#" + $(this).attr('id')).removeClass("has-error");
      	    }
			
          	// Se trata el error de fichero a parte, ya que el estilo
          	// debe ir en la etiqueta y no en el propio elemento
			if (!$('#file')[0].checkValidity()) {
					$("#file").removeClass("has-error");
					$(".custom-file-label").addClass("has-error");
				}
      	    
      	  });
		  
		  if ($('#platform option:selected').val() == "-1"){
			$('#platform').removeClass("has-error");
			$('#platform').addClass("has-error");
		  }else{
			$('#platform').removeClass("has-error");
		  }
		  
		  if ($('#serviceTypes option:selected').val() == "-1"){
		  	$('#serviceTypes').removeClass("has-error");	
		  	$('#serviceTypes').addClass("has-error");
		  }else{
			$('#serviceTypes').removeClass("has-error");
		  }
		  
		  if ($('#timer option:selected').val() == "-1"){
			$('#timer').removeClass("has-error");
			$('#timer').addClass("has-error");
		  }else{
			$('#timer').removeClass("has-error");
		  }
		  
		  if ($('#alarm option:selected').val() == "-1"){
			$('#alarm').removeClass("has-error");
			$('#alarm').addClass("has-error");
		  }else{
			$('#alarm').removeClass("has-error");
		  }
		  
	  } else{
		  $.ajax({
			  type: "POST",
			  url: saveserviceaction,
			  data: formData,
			  processData: false,
			  contentType: false,
			  success: function(data){
				  var errores = JSON.parse(data.error);
				  
				  if (data.error != null){
					  jQuery.each(errores, function(i, val) {
					  	$('#serviceForm *').filter('span').each(function(){
							if (i == $(this).attr('id')){
								$("#" + i).text(val);
							}
						});
					  });
				  }else{
					 // Es necesario hacer la limpieza del formulario por partes,
					 // ya que de otra manera se producen fallos de funcionamiento
					 // en los combos.
					 $('#serviceForm').trigger("reset");
					 $('#endpoint').attr('value', '');
					 $('#serviceTypes').val('-1');
					 $(".custom-file-label").attr('data-content', '');
					 $(".custom-file-label").text('');
					  $('#serviceForm *').filter('span').each(function(){
							$(this).text('');
						});
				  }
				  
				  hide();
				  tblService.row.add($(data.data)).draw(false);
				  tblService.rows().invalidate($(data.data)).draw(false);
				  
				  $('#serviceForm *').filter(':input').each(function(){
					 $("#" + $(this).attr('id')).removeClass("has-error");
				  });
				  
				  $('#platform').removeClass("has-error");
				  $('#serviceTypes').removeClass("has-error");
				  $('#timer').removeClass("has-error");
				  $('#alarm').removeClass("has-error");
				  $('#file').removeClass("has-error");
				  
				  if ($('#errorModalService').length > 0){
					 $('#errorModalService').remove();
				   }
				  
			  },
			  error:function(data){
				  hide();
				  if (data.error == "-1"){
					  if ($('#errorModalService').length == 0){
					  	$('#serviceForm').append('<div id="errorModalService" class="alert alert-danger" role="alert"><strong>' + [[#{service.admin.error.sameName}]] + '</strong></div>');
					  }
				  }else{
					  if ($('#errorModalService').length == 0){
					  	$('#serviceForm').append('<div id="errorModalService" class="alert alert-danger" role="alert"><strong>' + [[#{message.error}]] + '</strong></div>');
					  }
				  }
			  }
			});
	  }
	});
	
});	

function loadEditServiceTypes(idPlatform, serviceType) {
	
	$.getJSON(urlLoadServiceTypes, {
    	idPlatform : idPlatform
    }, function(data) {
        var html = '<option value="-1">' + selectServiceTypeText + '</option>';
        var len = data.length;
        for ( var i = 0; i < len; i++) {
        	if (serviceType == data[i]) {
            	html += '<option selected="selected" value="' + data[i] + '">'
                    + data[i] + '</option>';
        	} else {
        		html += '<option value="' + data[i] + '">'
                + data[i] + '</option>';
        	}
                    
        }
        html += '</option>';
        $('#serviceTypes').html(html);
        
    });
	
}

function cleanForm(f){
	
	$(f + ' *').filter(':input').each(function(){
		$(this).val('');
		$(this).next(".custom-file-label").attr('data-content', '');
		$(this).next(".custom-file-label").text('');
	});
	
	$(f + ' *').filter('span').each(function(){
		$(this).text('');
	});
	
	$(f + ' *').filter('select').each(function(){
		$(this).value = -1;
	});
}


function cleanServiceForm() {
	
	// Es necesario hacer la limpieza del formulario por partes,
	 // ya que de otra manera se producen fallos de funcionamiento
	 // en los combos.
	 $('#serviceForm').trigger("reset");
	 $('#endpoint').attr('value', '');
	 $('#serviceTypes').val('-1');
	 $(".custom-file-label").attr('data-content', '');
	 $(".custom-file-label").text('');
	
}

function checkTypeTime(id){
	var numValue =  $(id)[0].value;
	if (numValue.indexOf(':') != -1){
		var splitValue = numValue.split(':');
		if (splitValue.length == 2){
			numValue += ":00"
		}
	}
	return numValue;
}
function timeToMillisecond(s){
	var numValue =  s;
	
	if (numValue.indexOf(':') != -1){
		var splitValue = numValue.split(':');
		var finalValue = 0;
		if (splitValue.length == 2){
			finalValue = (+splitValue[0]) * 60 * 60 + (+splitValue[1]) * 60;
		} else if (splitValue.length == 3){
			finalValue = (+splitValue[0]) * 60 * 60 + (+splitValue[1]) * 60 + (+splitValue[2]);
		}
		finalValue = finalValue * 1000;
	}else{
		finalValue = numValue;
	}
	
	
	return finalValue;
}
function millisecondToTime(s){
	
	function pad(n, z) {
		z = z || 2;
		return ('00' + n).slice(-z);
	}
	var ms = s % 1000;
	s = (s - ms) / 1000;
	var secs = s % 60;
	s = (s - secs) / 60;
	var mins = s % 60;
	var hrs = (s - mins) / 60;
 	return pad(hrs) + ':' + pad(mins) + ':' + pad(secs);
}
function checkIfDisabledEndpoint(serviceTypes) {
	
	hide();
	
	if (serviceTypes.includes('OCSP') || serviceTypes.includes('RFC3161')) {
		
		$("#nameWsdl").removeAttr("required");
		$("#nameWsdl").prop('readonly', true);
		$("#nameWsdl").val('');

	} else {
		$("#nameWsdl").prop('required',true);
		$("#nameWsdl").prop('readonly', false);
	}
}
$("input[type=file]").change(function () {
	  var fieldVal = $(this).val();
	  // Change the node's value by removing the fake path (Chrome)
	  fieldVal = fieldVal.replace("C:\\fakepath\\", "");
	  if (fieldVal != undefined || fieldVal != "") {
		    $(this).next(".custom-file-label").attr('data-content', fieldVal);
		    $(this).next(".custom-file-label").text(fieldVal);
		  }
	});
	
	
function str2bytes (str) {
	   var bytes = new Uint8Array(str.length);
	   for (var i=0; i<str.length; i++) {
	      bytes[i] = str.charCodeAt(i);
	    }
	    return bytes;
	}
function downloadFile(idFile, fileName) {
	loading();
	
	var downloadFile =/*[[@{/downloadFile}]]*/;
	
	$.ajax({
		type: "POST",
		data:$.param({'idFile':idFile}),
		url: downloadFile,
		success: function(data) {
			hide();
			var blob = new Blob([str2bytes(data)], {type: "application/zip"});
						
			var link=document.createElement('a');
			link.href=window.URL.createObjectURL(blob);
			link.download=fileName;
			link.target="_blank";
			link.click();
  		}
	})
	
}
</script>